// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// F [author] rhyme_lph
// O [email]  rhymelph@gmail.com
// Q [github] https://github.com/rhymelph

import 'dart:async';

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/employee_contact_entity.dart';
import 'package:finance_app/src/http_service/http_employee_contact_service.dart';
import 'package:finance_app/src/mixin/format_group_map_mixin.dart';
import 'package:finance_app/src/mixin/search_data_list_mixin.dart';
import 'package:finance_app/src/provider/hr_payroll/hr_and_payroll_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/views/employee_provider.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/utils/reg_exp_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/date_time_select_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/normal_info_bottom_sheet.dart';
import 'package:flutter/material.dart';

class MarkAsResignedProvider extends BaseProvider<List<EmployeeContactEntity>>
    with SearchDataListMixin, FormatGroupMapLocalMixin<EmployeeContactEntity> {
  EmployeeContactEntity currentSelect;

  @override
  Future get dataFuture => HttpEmployeeContactService.contactList('open');

  @override
  FutureOr<List<EmployeeContactEntity>> transformData(
      List<EmployeeContactEntity> d, bool isCache) async {
    groupMap.clear();
    contactToMap(data);
    return d;
  }

  void onSelectEmployee(EmployeeContactEntity _data) {
    unFocus();
    update();
    currentSelect = _data;
    update();
    obtainContext?.call((context) async {
      DateTime selectDateTime = await showDateTimeSelectBottomSheet(
          context, 'Resignation Date', null,
          withinFinancialYear: false);
      if (selectDateTime != null) {
        bool isSuccess = await showEmployeeMarkAsResignedNormalInfoBottomSheet(
            context,
            dateTime: selectDateTime);
        if (isSuccess == true) {
          isSuccess = false;
          String resignedDate =
              DateTimeUtils.formatDateTime(selectDateTime, 'yyyy-MM-dd');

          await post(
              HttpEmployeeContactService.resignContact(_data.id, resignedDate),
              autoHandler: AutoHandler.Toast,
              loadingTip: 'Loading', onSuccess: (result) {
            isSuccess = true;
          });
          if (isSuccess) {
            // data.remove(_data);
            // data = await transformData(data, false);
            // update();
            await showEmployeeMarkResignedSuccessBottomSheet(context);
            Providers.get<HrAndPayrollProvider>(
                    RouterGenProviders.hrAndPayrollPage, null)
                ?.getChildProvider<EmployeeProvider>()
                ?.updateResigned(_data.id, resignedDate);
            if (!Config.hasPermission(PermissionUtils.homeDashboard))
              Config.dashboardProvider
                  ?.getChildProvider<HrAndPayrollProvider>()
                  ?.getChildProvider<EmployeeProvider>()
                  ?.updateResigned(_data.id, resignedDate);
            Navigator.of(context).pop();
          }
        }
      } else {
        currentSelect = null;
        update();
      }
    });
  }

  void contactToMap(List<EmployeeContactEntity> list) {
    sortGroupToMap(
      list,
      sort: (a, b) => sortNameFirst(a, b, (t) => t.name),
      filter: _onFilter,
      group: (a) => groupFirstName(a, (t) => t.name),
    );
  }

  @override
  void searchRefreshData(searchData) {
    transformData(data, false);
    update();
  }

  bool _onFilter(EmployeeContactEntity a) {
    if (RegExpUtils.getSearchRegExp(searchController.text).hasMatch(a.name)) {
      return true;
    }
    return false;
  }
}
